package xyz.quanguanjia.masterboy;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.widget.Toast;

import com.luck.picture.lib.basic.PictureSelectionCameraModel;
import com.luck.picture.lib.basic.PictureSelectionSystemModel;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.interfaces.OnResultCallbackListener;

import java.util.ArrayList;
import java.util.HashMap;

import xyz.quanguanjia.masterboy.model.MBDAccountInfoModel;
import xyz.quanguanjia.masterboy.view.MBDActionSheetDialog;

public class MBDUploadGroupActivity extends AppCompatActivity {

    private RecyclerView recyclerView;

    private MBDUploadGroupRecycleAdapter adapter;
    private ArrayList<MBDUploadGroupModel> mUploadGroupModels;

    private int position;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_upload_group);
        this.mUploadGroupModels = this.uploadGroupModels();

        //导航栏
        Toolbar toolbar = findViewById(R.id.toolbar);
        MBDToolbarUtils.setCenterTitle(toolbar, "上传群");

        MBDToolbarUtils.backButtonClicked(toolbar, new Runnable() {
            @Override
            public void run() {
                finish();
            }
        });


        SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swipeRefreshLayout);
        this.recyclerView = findViewById(R.id.recyclerView);

        // 设置下拉刷新监听器
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                // 在这里执行下拉刷新的操作
                // 当刷新完成后，调用 swipeRefreshLayout.setRefreshing(false); 结束刷新状态

                swipeRefreshLayout.setRefreshing(false);
            }
        });

        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);

        this.adapter = new MBDUploadGroupRecycleAdapter(this.mUploadGroupModels);

        ActivityResultLauncher<Intent> launcher = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
                    @Override
                    public void onActivityResult(ActivityResult rst) {
                        if (rst.getResultCode() == RESULT_OK) {
                            MBDUploadGroupModel model = MBDUploadGroupActivity.this.mUploadGroupModels.get(MBDUploadGroupActivity.this.position);

                            model.detail = rst.getData().getStringExtra("key");

                            adapter.notifyDataSetChanged();
                        }

                    }
                });

        MBDUploadGroupItemDecoration hi = new MBDUploadGroupItemDecoration(new MBDUploadGroupItemDecoration.UploadGroupItemClickListener() {
            @Override
            public void onItemClick(int position) {
                MBDUploadGroupActivity.this.position = position;

                MBDUploadGroupModel model = MBDUploadGroupActivity.this.mUploadGroupModels.get(MBDUploadGroupActivity.this.position);
                if (model.type == MBDUploadGroupModel.TYPE_GROUP_LOGO || model.type == MBDUploadGroupModel.TYPE_GROUP_CODE) {

                    MBDUploadGroupActivity.this.showActionSheet();

                } else {
                    Intent intent = new Intent(MBDUploadGroupActivity.this, MBDModifyInfoActivity.class);
                    intent.putExtra("title","" + model.name);
                    launcher.launch(intent);
                }

            }
        });
        recyclerView.addItemDecoration(hi);

        adapter.clickListener(new MBDUploadGroupRecycleAdapter.MBDGroupDetailViewHolder.ClickListener() {
            @Override
            public void confirmButtonClicked() {
                boolean hasBreak = false;

                HashMap<String,String> detailHashMap = new HashMap<>();
                for (int i = 0; i < MBDUploadGroupActivity.this.mUploadGroupModels.size(); i++) {
                    MBDUploadGroupModel model = MBDUploadGroupActivity.this.mUploadGroupModels.get(i);

                    if (model.type == MBDUploadGroupModel.TYPE_GROUP_TYPE) {
                        if (model.detail.equals(MBDUploadGroupModel.EMPTY_GROUP_TYPE)) {
                            Toast.makeText(MBDUploadGroupActivity.this, "请选择群类型", Toast.LENGTH_SHORT).show();
                            hasBreak = true;
                            break;
                        } else {
                            detailHashMap.put("groupType","1");
                            continue;
                        }

                    }

                    if (model.type == MBDUploadGroupModel.TYPE_GROUP_NAME) {
                        if (model.detail.equals(MBDUploadGroupModel.EMPTY_GROUP_NAME)) {
                            Toast.makeText(MBDUploadGroupActivity.this, "请输入群名", Toast.LENGTH_SHORT).show();
                            hasBreak = true;
                            break;
                        } else {
                            detailHashMap.put("groupName",model.detail);
                            continue;
                        }

                    }

                    if (model.type == MBDUploadGroupModel.TYPE_GROUP_DESC ){
                        if ( model.detail.equals(MBDUploadGroupModel.EMPTY_GROUP_DESC)) {
                            Toast.makeText(MBDUploadGroupActivity.this, "请输入群描述", Toast.LENGTH_SHORT).show();
                            hasBreak = true;
                            break;
                        } else {
                            detailHashMap.put("groupDesc",model.detail);
                            continue;
                        }

                    }

                    if (model.type == MBDUploadGroupModel.TYPE_GROUP_ADMIN ){
                        if ( model.detail.equals(MBDUploadGroupModel.EMPTY_GROUP_ADMIN)) {
                            Toast.makeText(MBDUploadGroupActivity.this, "请设置群管理员", Toast.LENGTH_SHORT).show();
                            hasBreak = true;
                            break;
                        } else {
                            detailHashMap.put("groupManager",model.detail);
                            continue;
                        }

                    }

                    if (model.type == MBDUploadGroupModel.TYPE_GROUP_LOGO){
                        if (model.detail.equals(MBDUploadGroupModel.EMPTY_GROUP_LOGO)) {
                            Toast.makeText(MBDUploadGroupActivity.this, "请上传群Logo", Toast.LENGTH_SHORT).show();
                            hasBreak = true;
                            break;
                        } else {
                            detailHashMap.put("groupLogo",model.detail);
                            continue;
                        }
                    }

//                    if (model.type == MBDUploadGroupModel.TYPE_GROUP_CODE){
//                        if (model.detail.equals(MBDUploadGroupModel.EMPTY_GROUP_CODE)) {
//                            Toast.makeText(MBDUploadGroupActivity.this, "请上传群Logo", Toast.LENGTH_SHORT).show();
//                            hasBreak = true;
//                            break;
//                        } else {
//                            detailModel.groupLogo = model.detail;
//                            continue;
//                        }
//                    }

                }
                if (!hasBreak) {
                    MBDUploadGroupActivity.this.uploadGroupInfo(detailHashMap);
                }

            }
        });

        recyclerView.setAdapter(adapter);
    }

    private void uploadGroupInfo(HashMap<String,String> params) {
        assert null!= params;

        String userId = MBDAccountInfoModel.current().getUserId();
        if (TextUtils.isEmpty(userId)) {
            MBDUserCenter.shared().setToken("");
            MBDAccountInfoModel.clear();
            Toast.makeText(MBDUploadGroupActivity.this, "请重新登录！", Toast.LENGTH_SHORT).show();
            return;
        }

        MBDHttpClient.shared().doRequest(ServiceType.SERVICE_GROUP_INFO_SAVE, params, new MBDHttpClient.Callback() {
            @Override
            public void completion(boolean success, Error error, MBDModelResponse response) {
                if (success) {
                    Toast.makeText(MBDUploadGroupActivity.this, "创建群成功！", Toast.LENGTH_SHORT).show();
                    MBDUploadGroupActivity.this.finish();
                } else {
                    Toast.makeText(MBDUploadGroupActivity.this, error.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }
        });

    }

    private void showActionSheet() {
        MBDActionSheetDialog actionSheetDialog = new MBDActionSheetDialog(this);
        actionSheetDialog.addMenuItem("拍照").addMenuItem("从手机相册选择");
        actionSheetDialog.setMenuListener(new MBDActionSheetDialog.MenuListener() {
            @Override
            public void onItemSelected(int position, String item) {
                if (0 == position) {
                    MBDUploadGroupActivity.this.takePhoto();
                } else {
                    MBDUploadGroupActivity.this.selectImage();
                }

            }

            @Override
            public void onCancel() {
//                    Toast.makeText(MainActivity.this, "onCancel", Toast.LENGTH_SHORT).show();
            }
        });
        actionSheetDialog.show();
    }

    private void takePhoto() {
        PictureSelector pictureSelector = PictureSelector.create(this);
        PictureSelectionCameraModel cameraModel = pictureSelector.openCamera(SelectMimeType.ofImage());
        cameraModel.setCompressEngine(new MBDCompressFileEngine());
        cameraModel.setCropEngine(new MBDCropEngine(this,16,9));

        cameraModel.forResult(new OnResultCallbackListener<LocalMedia>() {
            @Override
            public void onResult(ArrayList<LocalMedia> result) {
                assert result.size() > 0;
                LocalMedia media = result.get(0);
                //获取的压缩图片的路径
                uploadGroupPic(media.getCompressPath());
            }

            @Override
            public void onCancel() {

            }
        });
    }

    private void selectImage() {

        PictureSelector pictureSelector = PictureSelector.create(this);

        PictureSelectionSystemModel systemModel = pictureSelector.openSystemGallery(SelectMimeType.ofImage());
        systemModel.setCropEngine(new MBDCropEngine(this,16,9));
        systemModel.setCompressEngine(new MBDCompressFileEngine());
        systemModel.forSystemResult(new OnResultCallbackListener<LocalMedia>() {
            @Override
            public void onResult(ArrayList<LocalMedia> result) {
                assert result.size() > 0;

                LocalMedia media = result.get(0);

                uploadGroupPic(media.getCompressPath());
            }

            @Override
            public void onCancel() {

            }
        });
    }

    private void loadImage(String urlPath){
        MBDUploadGroupModel model = this.mUploadGroupModels.get(this.position);
        //二次确认下
        boolean modelIsOk = model.type == MBDUploadGroupModel.TYPE_GROUP_LOGO || model.type == MBDUploadGroupModel.TYPE_GROUP_CODE;
        assert modelIsOk;

        model.detail = urlPath;
        this.adapter.notifyDataSetChanged();
    }

    private void uploadGroupPic(String filePath) {
        assert !TextUtils.isEmpty(filePath);

        MBDHttpClient.shared().doPostFileRequest(filePath, null, new MBDHttpClient.Callback() {
            @Override
            public void completion(boolean success, Error error, MBDModelResponse response) {

                if (success && (response.data instanceof String)) {
                    loadImage((String) response.data);
                } else {
                    Toast.makeText(MBDUploadGroupActivity.this, error.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }
        });

    }

    private ArrayList<MBDUploadGroupModel> uploadGroupModels() {
        ArrayList<MBDUploadGroupModel> list = new ArrayList();
        MBDUploadGroupModel model1 = new MBDUploadGroupModel();
        model1.name = "群类型";
        model1.detail = MBDUploadGroupModel.EMPTY_GROUP_TYPE;
        model1.type = MBDUploadGroupModel.TYPE_GROUP_TYPE;
        list.add(model1);

        MBDUploadGroupModel model2 = new MBDUploadGroupModel();
        model2.name = "群名";
        model2.detail = MBDUploadGroupModel.EMPTY_GROUP_NAME;
        model2.type = MBDUploadGroupModel.TYPE_GROUP_NAME;
        list.add(model2);

        MBDUploadGroupModel model4 = new MBDUploadGroupModel();
        model4.name = "群描述";
        model4.detail = MBDUploadGroupModel.EMPTY_GROUP_DESC;
        model4.type = MBDUploadGroupModel.TYPE_GROUP_DESC;
        list.add(model4);

        MBDUploadGroupModel adminModel = new MBDUploadGroupModel();
        adminModel.name = "群主（或管理员）";
        adminModel.detail = MBDUploadGroupModel.EMPTY_GROUP_ADMIN;
        adminModel.type = MBDUploadGroupModel.TYPE_GROUP_ADMIN;
        list.add(adminModel);

        MBDUploadGroupModel logoModel = new MBDUploadGroupModel();
        logoModel.name = "群Logo";
        logoModel.detail = MBDUploadGroupModel.EMPTY_GROUP_LOGO;
        logoModel.type = MBDUploadGroupModel.TYPE_GROUP_LOGO;
        list.add(logoModel);

        MBDUploadGroupModel codeModel = new MBDUploadGroupModel();
        codeModel.name = "群二维码";
        codeModel.detail = MBDUploadGroupModel.EMPTY_GROUP_CODE;
        codeModel.type = MBDUploadGroupModel.TYPE_GROUP_CODE;
        list.add(codeModel);

        MBDUploadGroupModel model3 = new MBDUploadGroupModel();
//        model3.name = "群名";
//        model2.detail = "点此设置群名";
        model3.type = MBDUploadGroupModel.TYPE_GROUP_CONFIRM_BUTTON;
        list.add(model3);

        return list;
    }
}